import router, {
  constantRoutes
} from '@/router'
import {
  getRouters
} from '@/api/router'
import Layout from '@/layout/index'

// 匹配views里面所有的.vue文件
const modules =
  import.meta.glob('./../../views/**/*.vue')
const rdata = [{
  path: '/system',
  component: "Layout",
  hidden: false,
  redirect: 'user',
  name: "system",
  meta: {
    title: '系统管理',
    icon: 'system',
    affix: false
  },
  children: [{
      path: 'user',
      component: "system/user",
      name: 'user',
      meta: {
        title: '用户管理',
        icon: 'user'
      }
    },
    {
      path: 'role',
      component: "system/role",
      name: 'role',
      meta: {
        title: '角色权利',
        icon: 'peoples'
      }
    },
    {
      path: 'menu',
      component: "system/menu",
      name: 'menu',
      meta: {
        title: '菜单管理',
        icon: 'menu'
      }
    }
  ]
}];
const usePermissionStore = defineStore(
  'permission', {
    state: () => ({
      routes: [],
      addRoutes: [],
      sidebarRouters: []
    }),
    actions: {
      setSidebarRouters(routes) {
        this.sidebarRouters = routes
      },
      generateRoutes() {
        return new Promise(resolve => {
          // 向后端请求路由数据
          // const sdata = JSON.parse(JSON.stringify(res.data))
          // const rdata = JSON.parse(JSON.stringify(res.data))
          // const defaultData = JSON.parse(JSON.stringify(res.data))
          getRouters().then(res => {
            if (res.code == 200) {
              const sdata = JSON.parse(JSON.stringify(res.data));
              const sidebarRoutes = filterAsyncRouter(sdata);
              if (this.sidebarRouters.length <= 1) {
                this.routes = constantRoutes;
                sidebarRoutes.forEach(route => {
                  router.addRoute(route)
                });
                this.addRoutes = sdata;
                this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
              }
              resolve(sidebarRoutes);
            }
          });
        })
      }
    }
  })
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterChildren(route.children);
    } else {
      delete route['children'];
      delete route['redirect'];
    }
    return true
  })
}

function filterChildren(childrenMap) {
  var children = []
  childrenMap.forEach((el, index) => {
    el.component = loadView(el.component);
    children = children.concat(el);
  })
  return children
}


export const loadView = (view) => {
  let component;
  for (const path in modules) {
    const dir = path.split('views/')[1].split('.vue')[0];
    if (dir === view) {
      component = () => modules[path]();
    }
  }
  return component;
}

export default usePermissionStore